<template>
  <div class="p-4 max-w-2xl mx-auto">
    <h1 class="text-2xl font-bold mb-4">在线打牌/麻将计分板</h1>
    <div v-if="!gameStarted" class="space-y-4">
      <div>
        <label class="font-semibold">选择游戏类型：</label>
        <select v-model="gameType" class="border rounded px-2 py-1">
          <option value="poker">扑克牌</option>
          <option value="mahjong">麻将</option>
        </select>
      </div>
      <div>
        <label class="font-semibold">玩家人数：</label>
        <input type="number" v-model.number="playerCount" min="2" max="8" class="border rounded px-2 py-1 w-16" />
      </div>
      <div>
        <label class="font-semibold">输入玩家姓名：</label>
        <div class="space-y-1">
          <input v-for="(name, idx) in playerNames" :key="idx" v-model="playerNames[idx]" placeholder="玩家{{ idx+1 }}" class="border rounded px-2 py-1 w-40 mr-2" />
        </div>
      </div>
      <button @click="startGame" class="bg-blue-500 text-white px-4 py-2 rounded">生成计分板</button>
    </div>

    <div v-else>
      <div class="mb-4 flex items-center justify-between">
        <div>
          <span class="font-semibold">游戏类型：</span>{{ gameType === 'poker' ? '扑克牌' : '麻将' }}
          <span class="ml-4 font-semibold">房间号：</span>{{ redisKey }}
        </div>
        <button @click="copyShareLink" class="bg-green-500 text-white px-3 py-1 rounded">复制分享链接</button>
      </div>
      <div class="overflow-x-auto">
        <table class="min-w-full border text-center">
          <thead>
            <tr>
              <th class="border px-2 py-1">局数</th>
              <th v-for="p in players" :key="p.id" class="border px-2 py-1">{{ p.name }}</th>
              <th class="border px-2 py-1">操作</th>
            </tr>
          </thead>
          <tbody>
            <template v-for="(round, idx) in rounds" :key="idx">
              <tr>
                <td class="border px-2 py-1">{{ round.roundNo }}</td>
                <td v-for="p in players" :key="p.id" class="border px-2 py-1">{{ getRoundNet(round, p.id) }}</td>
                <td class="border px-2 py-1 text-xs">
                  <button @click="editRound(idx)" class="text-blue-500">编辑</button>
                  <button @click="deleteRound(idx)" class="text-red-500 ml-2">删除</button>
                  <button @click="toggleDetail(idx)" class="ml-2 text-gray-600 text-xs">{{ round.showDetail ? '收起' : '查看明细' }}</button>
                </td>
              </tr>
              <tr v-if="round.showDetail">
                <td class="border px-2 py-1" :colspan="players.length + 2">
                  <div class="text-left">
                    <div class="mb-2 font-semibold">第 {{ round.roundNo }} 局 明细（from -> to）</div>
                    <div class="overflow-auto">
                      <table class="border text-sm">
                        <thead>
                          <tr>
                            <th class="border px-2 py-1">从 / 到</th>
                            <th v-for="to in players" :key="to.id" class="border px-2 py-1">{{ to.name }}</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr v-for="from in players" :key="from.id">
                            <td class="border px-2 py-1 font-medium">{{ from.name }}</td>
                            <td v-for="to in players" :key="to.id" class="border px-2 py-1">
                              <span v-if="from.id === to.id">-</span>
                              <span v-else>{{ (round.transfers && round.transfers[from.id] && round.transfers[from.id][to.id]) || 0 }}</span>
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </td>
              </tr>
            </template>
            <tr>
              <td class="border px-2 py-1 font-bold">总分</td>
              <td v-for="p in players" :key="p.id" class="border px-2 py-1 font-bold">{{ totalScore(p.id) }}</td>
              <td class="border"></td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="mt-4">
        <h2 class="font-semibold mb-2">添加新一局（请输入每人输给每位对手的分数）</h2>
        <div class="mb-2 text-sm text-gray-600">填写规则：填写 "从 -> 到" 的金额。输的人填写自己输给其他人的分数（为正数）。如果没有输给某人，填 0。</div>
        <div class="overflow-auto mb-2">
          <table class="border text-sm">
            <thead>
              <tr>
                <th class="border px-2 py-1">从 / 到</th>
                <th v-for="to in players" :key="to.id" class="border px-2 py-1">{{ to.name }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="from in players" :key="from.id">
                <td class="border px-2 py-1 font-medium">{{ from.name }}</td>
                <td v-for="to in players" :key="to.id" class="border px-2 py-1">
                  <span v-if="from.id === to.id">-</span>
                  <input v-else type="number" v-model.number="newTransfers[from.id][to.id]" class="border rounded px-2 py-1 w-20" />
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <button @click="addRound" class="bg-blue-500 text-white px-4 py-2 rounded">添加本局</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const gameType = ref('poker')
const playerCount = ref(4)
const playerNames = ref(['', '', '', ''])
const players = ref([])
const rounds = ref([])
const newTransfers = reactive({})
const gameStarted = ref(false)
const redisKey = ref('')
const route = useRoute()
const router = useRouter()

function randomKey(len = 10) {
  const chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  let str = ''
  for (let i = 0; i < len; i++) str += chars[Math.floor(Math.random() * chars.length)]
  return str
}

function startGame() {
  // 校验
  const names = playerNames.value.map(n => n.trim()).filter(Boolean)
  if (names.length < 2) return alert('请至少输入2个玩家姓名')
  players.value = names.map((name, idx) => ({ id: 'p' + idx, name }))
  // 初始化转账矩阵输入
  initTransfersForPlayers(players.value)
  // 生成redisKey
  redisKey.value = randomKey()
  // 初始化
  rounds.value = []
  gameStarted.value = true
  // 跳转带key的链接
  router.replace({ path: '/live-tools/scoreboard', query: { key: redisKey.value } })
}

function addRound() {
  // 校验 transfers
  const transfers = {}
  for (const from of players.value) {
    if (!newTransfers[from.id]) return alert('请完整填写转账矩阵')
    transfers[from.id] = {}
    for (const to of players.value) {
      if (from.id === to.id) continue
      const v = newTransfers[from.id][to.id]
      if (typeof v !== 'number') return alert('请填写所有玩家之间的数值（为空请填写0）')
      transfers[from.id][to.id] = v
    }
  }
  const net = computeNetFromTransfers(transfers)
  rounds.value.push({ roundNo: rounds.value.length + 1, transfers: transfers, scores: net, extraInfo: {}, showDetail: false })
  // reset inputs
  initTransfersForPlayers(players.value)
  saveToServer()
}

function computeNetFromTransfers(transfers) {
  const net = {}
  for (const p of players.value) net[p.id] = 0
  for (const fromId in transfers) {
    for (const toId in transfers[fromId]) {
      const v = Number(transfers[fromId][toId] || 0)
      net[toId] = (net[toId] || 0) + v
      net[fromId] = (net[fromId] || 0) - v
    }
  }
  return net
}

function getRoundNet(round, pid) {
  if (round.transfers) {
    const net = computeNetFromTransfers(round.transfers)
    return net[pid] || 0
  }
  return round.scores ? (round.scores[pid] || 0) : 0
}

function totalScore(pid) {
  return rounds.value.reduce((sum, r) => sum + Number(getRoundNet(r, pid) || 0), 0)
}

function editRound(idx) {
  const r = rounds.value[idx]
  // 如果存在 transfers，填充 newTransfers
  if (r.transfers) {
    for (const from of players.value) {
      for (const to of players.value) {
        if (from.id === to.id) continue
        newTransfers[from.id][to.id] = (r.transfers[from.id] && r.transfers[from.id][to.id]) || 0
      }
    }
  } else if (r.scores) {
    // 旧数据：无法还原具体对手金额，置为0，交给用户手动修改
    for (const from of players.value) {
      for (const to of players.value) {
        if (from.id === to.id) continue
        newTransfers[from.id][to.id] = 0
      }
    }
  }
  // 删除本局，用户编辑后重新添加
  rounds.value.splice(idx, 1)
}

function deleteRound(idx) {
  if (confirm('确定删除本局？')) {
    rounds.value.splice(idx, 1)
    saveToServer()
  }
}

function copyShareLink() {
  const url = `${location.origin}/live-tools/scoreboard?key=${redisKey.value}`
  navigator.clipboard.writeText(url)
  alert('分享链接已复制')
}

function toggleDetail(idx) {
  const r = rounds.value[idx]
  r.showDetail = !r.showDetail
}

function initTransfersForPlayers(pls) {
  for (const from of pls) {
    if (!newTransfers[from.id]) newTransfers[from.id] = {}
    for (const to of pls) {
      if (from.id === to.id) continue
      newTransfers[from.id][to.id] = 0
    }
  }
}


async function saveToServer() {
  if (!redisKey.value) return
  const payload = {
    redisKey: redisKey.value,
    gameType: gameType.value,
    players: players.value,
    rounds: rounds.value,
    createdAt: new Date().toISOString()
  }
  await fetch('/api/scoreboard', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  })
}


async function loadFromServer(key) {
  const res = await fetch(`/api/scoreboard?key=${key}`)
  if (!res.ok) return
  const data = await res.json()
  if (!data || !data.players) return
  gameType.value = data.gameType
  players.value = data.players
  // 兼容旧 rounds（可能只有 scores），并初始化显示控制字段
  rounds.value = (data.rounds || []).map(r => ({ ...r, showDetail: false }))
  gameStarted.value = true
  initTransfersForPlayers(players.value)
}

onMounted(() => {
  // 如果有key参数，加载数据
  const key = route.query.key
  if (key) {
    redisKey.value = key
    loadFromServer(key)
  }
})
</script>

<style scoped>
table th, table td { min-width: 60px; }
</style>
